package com.hotel.dao.impl;

import com.hotel.dao.RoomTypeDao;
import com.hotel.entity.RoomType;
import com.hotel.utils.JdbcUtils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author Str
 * @Date 2021/10/29 22:50
 * @Description :
 */
public class RoomTypeDaoImpl implements RoomTypeDao {

    @Override
    public List<RoomType> getRoomTypes() throws SQLException {
        String sql = "select * from roomtype ";
        return JdbcUtils.queryList(sql, RoomType.class);
    }

    @Override
    public RoomType getById(String id) {
        String sql = "select * from roomtype where id = ?";
        return JdbcUtils.queryObject(sql, RoomType.class, id);
    }

    /**
     * 获取搜索语句片段
     * map是url参数列表的map集合
     *
     * @return java.lang.String
     */
    @Override
    public String getSearchSQL(Map<String, Object> map) {
        //{ps}这个 map 进来这个方法之前先把 page, limit 拿掉。
        Set<String> keySet = map.keySet();
        StringBuilder sb = new StringBuilder();
        for (String key : keySet) {
            Object word = map.get(key);
            sb.append(" and " + key
                    + " like '%" + word + "%'");
        }
        return sb.toString();
    }

    /**
     * sqlPart是getSearchSQL方法的返回值
     *
     * @return int
     */
    @Override
    public int getCount(String sqlPart) throws SQLException {
        //{1}做 sql 拼接。
        String sql = "select count(*) from roomtype n " +
                " where n.id is not null " + sqlPart;
        System.out.println("getCount" + sql);
        //{2}查询数量。
        Long count = (Long) JdbcUtils.queryValue(sql);
        //{3}做类型转换 ----> int
        return count.intValue();
    }

    @Override
    public List<RoomType> getList(String sqlPart, Integer offset, Integer limit) throws SQLException {
        String sql = "select n.* from roomtype n " +
                " where n.id is not null " + sqlPart + " order by n.id limit ?, ?";
        List<RoomType> list = JdbcUtils.queryList(sql, RoomType.class, offset, limit);
        System.out.println("getRoomList"+list);
        return list;
    }

    @Override
    public int add(RoomType roomType) throws SQLException {
        String sqlAdd = "INSERT INTO `roomtype` VALUES (?, ?, ?, ?, now(), now());";
        return JdbcUtils.update(sqlAdd, roomType.getId(), roomType.getTypeName(), roomType.getDayPrice(), roomType.getHourPrice());
    }

    @Override
    public int update(RoomType roomType) throws SQLException {
        String sqlUpdate = "update roomtype set typeName=?,dayPrice=?,hourPrice=? where id=?;";
        return JdbcUtils.update(sqlUpdate, roomType.getTypeName(), roomType.getDayPrice(), roomType.getHourPrice(), roomType.getId());
    }

    @Override
    public int delete(String id) throws SQLException {
        String sqlDelete = "delete from roomtype where id=?";
        return JdbcUtils.update(sqlDelete, id);
    }
}
